using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
//using PCComm;

namespace PCComm
{
    public partial class frmMain : Form
    {
        //CommunicationManager comm = new CommunicationManager();
        ECMCommunication comm = new ECMCommunication(this); 
        string transType = string.Empty;
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
           LoadValues();
           SetDefaults();
           SetControlState();
        }

        private void cmdOpen_Click(object sender, EventArgs e)
        {
            comm.Parity = cboParity.Text;
            comm.StopBits = cboStop.Text;
            comm.DataBits = cboData.Text;
            comm.BaudRate = cboBaud.Text;
            comm.DisplayWindow = rtbDisplay;
            comm.PortName = cboPort.Text;
            comm.OpenPort();

            cmdOpen.Enabled = false;
            cmdClose.Enabled = true;
            cmdSend.Enabled = true;
        }

        /// <summary>
        /// Method to initialize serial port
        /// values to standard defaults
        /// </summary>
        private void SetDefaults()
        {
            cboPort.SelectedIndex = 0;
            cboBaud.SelectedText = "9600";
            cboParity.SelectedIndex = 0;
            cboStop.SelectedIndex = 1;
            cboData.SelectedIndex = 1;
        }

        /// <summary>
        /// methos to load our serial
        /// port option values
        /// </summary>
        private void LoadValues()
        {
            comm.SetPortNameValues(cboPort);
            comm.SetParityValues(cboParity);
            comm.SetStopBitValues(cboStop);
        }

        /// <summary>
        /// method to set the state of controls
        /// when the form first loads
        /// </summary>
        private void SetControlState()
        {
            rdoText.Checked = true;
            cmdSend.Enabled = false;
            cmdClose.Enabled = false;
        }

        private void cmdSend_Click(object sender, EventArgs e)
        {
            comm.WriteData(txtSend.Text);
        }

        private void rdoHex_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoHex.Checked == true)
            {
                comm.CurrentTransmissionType = PCComm.CommunicationManager.TransmissionType.Hex;
            }
            else
            {
                comm.CurrentTransmissionType = PCComm.CommunicationManager.TransmissionType.Text;
            }
        }

        private void rdoECM_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoECM.Checked == true)
            {
                comm.CurrentTransmissionType = PCComm.CommunicationManager.TransmissionType.ECM;
            }
            else
            {
                comm.CurrentTransmissionType = PCComm.CommunicationManager.TransmissionType.Text;
            }
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            comm.ClosePort();

            cmdOpen.Enabled = true;
            cmdClose.Enabled = false;
            cmdSend.Enabled = false;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
 
        private void btn_Write_data_Click(object sender, EventArgs e)
        {
            DataGridViewColumn newColumn = new DataGridViewColumn(dgRunTimeData.Columns[0].CellTemplate);
            newColumn.Name = "Hex_Data";
            dgRunTimeData.Columns.Add(newColumn);
        }

        private void btnSaveData_Click(object sender, EventArgs e)
        {
            using (CsvFileWriter writer = new CsvFileWriter("C:\\WriteTest.csv"))
            {
                CsvRow headerRow = new CsvRow();
                foreach (DataGridViewColumn dgColumn in dgRunTimeData.Columns)
                {
                    headerRow.Add(dgColumn.Name);
                }
                writer.WriteRow(headerRow);

                foreach (DataGridViewRow dgRow in dgRunTimeData.Rows)
                {
                    CsvRow row = new CsvRow();

                    foreach (DataGridViewCell cell in dgRow.Cells)
                    {
                        string str = (string)cell.FormattedValue;
                        row.Add(str);
                    }
                    writer.WriteRow(row);
                }

            }
        }

        private void btnReadCSV_Click(object sender, EventArgs e)
        {
            // Get the CSV file from the dialog box
            openFD.Title = "Choose CSV file for import";
            openFD.ShowDialog();
            string sCSVPath = openFD.FileName;

            using (CsvFileReader reader = new CsvFileReader(sCSVPath))
            {
                DataTable RunTimeDataTable = new DataTable();
                CsvRow row = new CsvRow();

                //read the first line and set as header
                reader.ReadRow(row);
                foreach(string sHeader in row)
                {
                    RunTimeDataTable.Columns.Add(sHeader);
                }

                //read the rest and build the row
                while (reader.ReadRow(row))
                {
                    //object[] array = new object[row.Count];
                    //for (int i = 0; i < row.Count; i++)
                    //{
                    //    array[i] = row[i];
                    //}
                    RunTimeDataTable.Rows.Add(row.ToArray());
                }
                dgRunTimeData.DataSource = RunTimeDataTable;
                dgRunTimeData.AutoResizeColumns();
                dgRunTimeData.RowHeadersVisible = false;
            }
        }        

        #region Column to string conversion
        /// <summary>
        /// method to convert a column from a DataGridView into a string
        /// <param> sColumnName="name"></param>
        /// <returns> a string containing all runtime data</returns>
        public string ColumntoString(string sDataGridName, string sColumnName)
        {
            string sHexData = "";
            DataGridView dg = (DataGridView)this.GetType().GetField(sDataGridName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
            for (int i = 0; i < dg.Rows.Count; i++)
            {
                sHexData = sHexData + dg.Rows[i].Cells[sColumnName].Value.ToString();
            }
            return sHexData;
        }
        #endregion
    }
}
